﻿using System;
using System.Linq;
using ReactiveGraph.Core;
using ReactiveGraph.Object;

namespace ReactiveGraph.Uat.ResolvableValueUat
{
    public class ResolvableValue<T> : ReactiveObject<ResolvableValue<T>>
    {
        public override void Initialize()
        {
            base.Initialize();
            ValidationState.Value = new ValidationState() { IsError = false };
            Current = new PropertyQueue<T>("Value", qVal => GetOrder(qVal.Name));
            AttachCustomProperty(Current);
            AttachBehaviour(ResetValidationOnValueChange());   
        }

        private IObservable<Unit> ResetValidationOnValueChange()
        {
            return from p in PropertyChanged(value => value.Current)
                   select ResetValidationState(); 
        }

        private Unit ResetValidationState()
        {
            ValidationState.Value =new ValidationState(){IsError = false};
            return new Unit();
        }

        private static object GetOrder(string name)
        {
            switch (name)
            {
                case "Loaded":
                    return 0;
                default:
                    return 999;
            }
        }

        public PropertyQueue<T> Current { get; private set; }
        public Property<bool> Resolving { get; private set; }
        public Property<ValidationState> ValidationState { get; private set; }
    }
}
